﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Authority.Core;
using System.Collections;

namespace Authority
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CbxDataBind();
            }
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            string userName = this.TbxUser.Text.Trim();
            User user = new User();
            user.userName = userName;

            PopedomTypes permissions = new PopedomTypes();
            if (CbxCreate.Checked) permissions = permissions.Add(PopedomTypes.Create);
            if (CbxDelete.Checked) permissions = permissions.Add(PopedomTypes.Delete);
            if (CbxModify.Checked) permissions = permissions.Add(PopedomTypes.Modify);
            if (CbxRead.Checked) permissions = permissions.Add(PopedomTypes.Read);
            if (CbxWrite.Checked) permissions = permissions.Add(PopedomTypes.Write);
            user.Permissions = permissions;

            Model.UsersModel userModel = new Model.UsersModel();
            Bll.UsersBll userBll = new Bll.UsersBll();
            userModel.UserName = user.userName;
            userModel.PermissionTypes = (int)user.Permissions;

            if (Request.QueryString["id"] != null)
            {
                userModel.Id = int.Parse(Request.QueryString["id"].ToString());
                userBll.Update(userModel);
            }
            else
            {
                userBll.Add(userModel);
            }
        }

        protected void CbxDataBind()
        {
            if (Request.QueryString["id"] != null)
            {
                this.BtnSave.Text = "保存";

                int id = int.Parse(Request.QueryString["id"].ToString());
                Bll.UsersBll userBll = new Bll.UsersBll();
                Model.UsersModel userModel = userBll.GetModel(id);
                int value = (int)userModel.PermissionTypes;
                PopedomTypes permissions = new PopedomTypes();
                Hashtable ht = permissions.GetPermission(value);

                this.TbxUser.Text = userModel.UserName;
                foreach (DictionaryEntry de in ht)
                {
                    if (de.Value.ToString() == "True")
                    {
                        CheckBox cb = this.form1.FindControl("Cbx" + de.Key) as CheckBox;
                        cb.Checked = true;
                    }
                }
            }
            else
            {
                this.BtnSave.Text = "添加";
            }
        }
    }
}